package top.fengyulou.xiaofeng.controller.admin;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.fengyulou.xiaofeng.common.*;
import top.fengyulou.xiaofeng.dto.UserDto;
import top.fengyulou.xiaofeng.enums.UserTypeEnum;
import top.fengyulou.xiaofeng.service.LoginService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author guochao
 * @version 1.0
 * @date 2022/1/26 1:37
 */
@Controller
public class AdminLoginController {

    @Resource
    private LoginService loginService;

    //登录页面
    @RequestMapping("/admin/login")
    public String login(HttpServletRequest request) {
        if (UserUtils.isLogin(request)) {
            return WebUtils.redirect("/admin/user/list");
        }
        return "admin-login";
    }

    //用户登录
    @RequestMapping("/admin/ajax/login")
    @ResponseBody
    public Jr ajaxLogin(HttpServletRequest request, UserDto userDto) {
        ValidatorUtil.require(userDto.getLoginName(), "账号");
        ValidatorUtil.length(userDto.getLoginName(), "账号", 1, 50);
        ValidatorUtil.require(userDto.getPassword(), "密码");

        if (loginService.login(userDto.getLoginName(), MyUtils.getMd5(userDto.getPassword()), UserTypeEnum.ADMIN.getCode(), request)) {
            return Jr.yes();
        }
        return Jr.no();
    }

    //退出登录
    @RequestMapping("/admin/logout")
    public String logout(HttpServletRequest request) {
        UserUtils.logout(request);
        return WebUtils.redirect("/admin/login");
    }
}
